import copy
import re
import qrcode

from PySide6.QtCore import QDateTime, Slot, Qt
from PySide6.QtWidgets import QMessageBox, QDialog, QTableWidgetItem, QMainWindow, QButtonGroup
from PySide6.QtGui import QIcon, QColor, QPixmap

from Devices.Chiot.BsDevs.ComDev.Forms.ComDevWindow import ComDevWindow
from Devices.Chiot.BsDevs.Plug.PlugDevice import PlugDevice
from Devices.Chiot.BsDevs.Plug.PlugParser import PlugParser
from Components.MessageBoxFunc import MessageBoxFunc

from Devices.Chiot.BsDevs.Plug.Forms.PlugWindow_UI import Ui_FormPlugWindow
from Devices.Chiot.BsDevs.Plug.Forms.TimerSetWindow import TimerSetWindow

from Funcs.Config import Config

# X-HM://007IUIPJCG3DU
def make_valid_filename(filename):
    invalid_chars = r'[^\w\s.-]'
    valid_filename = re.sub(invalid_chars, '_', filename)
    return valid_filename

class PlugWindow(ComDevWindow):
    # 0、窗体初始化、状态变量初始化
    def __init__(self, supportDevice, parent = None):
        # 注意在实现特有设备时，一定要先将其ui对象加载完毕
        super().__init__(supportDevice, parent)
        
        self.FullStatus = PlugDevice.PlugFullStatus()
        self.deviceName = supportDevice.deviceDisplayName

        self._ui = Ui_FormPlugWindow()
        self._ui.setupUi(self)
        self.initUiWindow()
        self.SetupUi(self._ui)

        self.__TimerSetWindow = TimerSetWindow()
        # self.testUi()

    def setHomekit(self):
        self._ui.radioButton_hotPlugCtrl.blockSignals(True)
        self._ui.radioButton_hotPlugCtrl.setChecked(True if self.FullStatus.hotPlug else False)
        self._ui.radioButton_hotPlugCtrl.blockSignals(False)

        self._ui.label_setupCode.setText(self.FullStatus.setupCode.strip())
        self._ui.label_setupPayload.setText(self.FullStatus.setupPayload.strip())
        
        # 生成二维码
        text = self.FullStatus.setupPayload.strip()
        if text == '':
            self.ShowMessageBox("生成二维码失败", "setupPayload为空!", QMessageBox.Critical, timeoutS=2000)
            return False

        file_path = "{}\\Logs\\{}\\{}.png".format(Config.GetCurrentPath(), self.deviceName, self._ui.label_mac.text())
        qr = qrcode.QRCode(
            box_size=5,
            border=4,
        )
        qr.add_data(text)
        qr.make(fit=True)
        img = qr.make_image(fill_color="black", back_color="white")
        img.save(file_path)
        self._ui.label_QRCode.setPixmap(QPixmap(file_path))#我的图片格式为png.与代码在同一目录下
        return True

     # 1、数据解析
    def setHeartbeatStatus(self):
        #定时器
        self._ui.tableWidget_timers.clearContents()
        self._ui.tableWidget_timers.setRowCount(0)
        for timer in self.FullStatus.timers:
            if timer != None:
                self.SetTimerToList(timer)

        #倒计时
        if 0 != self.FullStatus.delay.enable:
            self._ui.label_delayId.setText(self.FullStatus.delay.id)
            self._ui.dateTimeEdit_delayExecTime.setDateTime(QDateTime.fromSecsSinceEpoch(self.FullStatus.delay.end))
            self._ui.comboBox_delaySwitchCtrl.setCurrentIndex(self.FullStatus.delay.services[0].paraValue)
            self._ui.label_delayNotion.setVisible(False)
        else:
            self._ui.label_delayId.clear()
            self._ui.dateTimeEdit_delayExecTime.setDateTime(QDateTime.currentDateTime())
            self._ui.label_delayNotion.setVisible(True)

    def CmdRptStatusReceived(self, msgValue):
        if PlugParser.ParseRptStatus(msgValue, self.FullStatus):
            self.setFullStatus()

    def CmdHeartbeatReceived(self, msgValue):
        if PlugParser.ParseHeartbeat(msgValue, self.FullStatus):
            self.setFullStatus()
            self.setHeartbeatStatus()

    def CmdFullStatusReceived(self, msgValue):
        if PlugParser.ParseHomekitInfo(msgValue, self.FullStatus):
            self.setHomekit()

    def CmdMsgValueReceived(self, msgName, msgValue):
        pass

    def CmdRptCustomReceived(self, msgValue):
        if PlugParser.ParseCmdCustom(msgValue, self.FullStatus):
            self.setHomekit()

    # 2、运行状态
    def setFullStatus(self):
        self._ui.label_switchStatus.setText("打开" if self.FullStatus.switchStatus else "关闭")
        self._ui.label_memSwitchStatus.setText("打开" if self.FullStatus.memSwitchStatus else "关闭")
        self._ui.label_backlightStatus.setText("打开" if self.FullStatus.backlightStatus else "关闭")
        self._ui.label_chargingProStatus.setText("打开" if self.FullStatus.chargingProStatus else "关闭")

        self._ui.radioButton_switchCtrl.blockSignals(True)
        self._ui.radioButton_memSwitchCtrl.blockSignals(True)
        self._ui.radioButton_backlightCtrl.blockSignals(True)
        self._ui.radioButton_chargingProCtrl.blockSignals(True)

        self._ui.radioButton_switchCtrl.setChecked(True if self.FullStatus.switchStatus else False)
        self._ui.radioButton_memSwitchCtrl.setChecked(True if self.FullStatus.memSwitchStatus else False)
        self._ui.radioButton_backlightCtrl.setChecked(True if self.FullStatus.backlightStatus else False)
        self._ui.radioButton_chargingProCtrl.setChecked(True if self.FullStatus.chargingProStatus else False)

        self._ui.radioButton_switchCtrl.blockSignals(False)
        self._ui.radioButton_memSwitchCtrl.blockSignals(False)
        self._ui.radioButton_backlightCtrl.blockSignals(False)
        self._ui.radioButton_chargingProCtrl.blockSignals(False)
    
    # 3、设备控制
    @Slot(bool)
    def on_radioButton_switchCtrl_toggled(self, checked):
        if self.FullStatus.switchStatus != int(checked):
            cmd = PlugParser.PackSetAttr("switch", "on", int(checked))
            self.SendCommandText(cmd)

    @Slot(bool)
    def on_radioButton_memSwitchCtrl_toggled(self, checked):
        if self.FullStatus.memSwitchStatus != int(checked):
            cmd = PlugParser.PackSetAttr("memorySwitch", "on", int(checked))
            self.SendCommandText(cmd)

    @Slot(bool)
    def on_radioButton_backlightCtrl_toggled(self, checked):
        if self.FullStatus.backlightStatus != int(checked):
            cmd = PlugParser.PackSetAttr("backlight", "on", int(checked))
            self.SendCommandText(cmd)

    @Slot(bool)
    def on_radioButton_chargingProCtrl_toggled(self, checked):
        if bool(self.FullStatus.chargingProStatus) != int(checked):
            cmd = PlugParser.PackSetAttr("chargingPro", "on", int(checked))
            self.SendCommandText(cmd)
    
    @Slot(bool)
    def on_radioButton_hotPlugCtrl_toggled(self, checked):
        if bool(self.FullStatus.hotPlug) != checked:
            if checked:
                self.FullStatus.hotPlug = 1
                cmd = PlugParser.PackCustomCmd("enable_hot_plug", None)
            else:
                self.FullStatus.hotPlug = 0
                cmd = PlugParser.PackCustomCmd("disable_hot_plug", None)
            self.SendCommandText(cmd)

    # 4、定时器
    @Slot()
    def on_pushButton_addTimer_clicked(self):
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            timer = PlugDevice.Timer()
            self.__TimerSetWindow.GetTimer(timer)
            cmd = PlugParser.PackSetTimer(timer)
            print(cmd)
            self.SendCommandText(cmd)
    
    @Slot()
    def on_pushButton_delTimer_clicked(self):
        rowCount = self._ui.tableWidget_timers.currentRow()
        if rowCount >= 0:
            timer = copy.deepcopy(self.FullStatus.timers[rowCount])
            timer.week = 0
            cmd = PlugParser.PackSetTimer(timer)
            self.SendCommandText(cmd)

    @Slot(QTableWidgetItem)
    def on_tableWidget_timers_itemDoubleClicked(self, item):
        rowCount = item.row()
        timer = copy.deepcopy(self.FullStatus.timers[rowCount])

        self.__TimerSetWindow.SetTimer(timer)
        if QDialog.Accepted == self.__TimerSetWindow.exec():
            self.__TimerSetWindow.GetTimer(timer)
            cmd = PlugParser.PackSetTimer(timer)
            print(cmd)
            self.SendCommandText(cmd)

    @Slot()
    def on_pushButton_setDelay_clicked(self):
        delay = PlugDevice.Delay()

        delay.enable = True
        delay.end = self._ui.dateTimeEdit_delayExecTime.dateTime().toSecsSinceEpoch()
        #灯开关
        delay.services.clear()
        delay.services.append(PlugDevice.ServiceParams("switch", "on", self._ui.comboBox_delaySwitchCtrl.currentIndex()))
        
        cmd = PlugParser.PackSetDelay(delay)
        print(cmd)
        self.SendCommandText(cmd)

    @Slot()
    def on_pushButton_delDelay_clicked(self):
        if self.FullStatus.delay:
            delay = copy.deepcopy(self.FullStatus.delay)
            delay.enable = False
            # self._ui.dateTimeEdit_delayTime.setDateTime(QDateTime.currentDateTime())

            cmd = PlugParser.PackSetDelay(delay)
            print(cmd)
            self.SendCommandText(cmd)

    